package com.ziyucoding.springboot.labs.redislike.service.impl;

import com.ziyucoding.springboot.labs.redislike.common.CommonResponse;
import com.ziyucoding.springboot.labs.redislike.common.Constant;
import com.ziyucoding.springboot.labs.redislike.service.RedisLikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ziyucoding.springboot.labs.redislike.service.LikeService;

/**
 * 点赞服务 实现类
 *
 * @author ziyucoding
 * @date 2023-02-07
 **/
@Service("likeService")
@Slf4j
public class LikeServiceImpl implements LikeService {

    @Autowired
    private RedisLikeService redisLikeService;

    @Override
    public CommonResponse<Object> likeInfo(String infoId, String userId) {
        // 查询Redis是否已经存储为喜欢
        Integer status = redisLikeService.getLikeStatus(infoId, userId);
        if (status == Constant.LikedStatusEum.LIKE.getCode()) {
            // 已经存在喜欢
            return CommonResponse.createForSuccess("已经点赞该内容啦，请勿重复点赞！");
        }
        // 不存在或者之前是取消喜欢
        try {
            redisLikeService.saveLiked2Redis(infoId, userId);
            redisLikeService.inDecrementLikedCount(infoId, 1);
            return CommonResponse.createForSuccess("喜欢内容写入redis缓存成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResponse.createForError("喜欢内容写入redis缓存失败，请稍后重试！");
        }
    }

    @Override
    public CommonResponse<Object> dislikeInfo(String infoId, String userId) {
        // 查询Redis是否已经存储为取消喜欢
        Integer status = redisLikeService.getLikeStatus(infoId, userId);
        if (status == Constant.LikedStatusEum.UNLIKE.getCode()) {
            // 已经存在取消喜欢
            return CommonResponse.createForSuccess("已经取消点赞该内容啦，请勿重复取消点赞！");
        } else if (status == Constant.LikedStatusEum.NOT_EXIST.getCode()) {
            // 不存在取消喜欢，修改状态，增加0条
            redisLikeService.unlikeFromRedis(infoId, userId);
            redisLikeService.inDecrementLikedCount(infoId, 0);
            return CommonResponse.createForSuccess("取消喜欢内容写入redis缓存成功");
        } else {// 之前已经喜欢，则修改状态,并喜欢数-1
            try {
                redisLikeService.unlikeFromRedis(infoId, userId);
                redisLikeService.inDecrementLikedCount(infoId, -1);
                return CommonResponse.createForSuccess("取消喜欢内容写入redis缓存成功");
            } catch (Exception e) {
                log.error(e.getMessage());
                return CommonResponse.createForError("取消喜欢内容写入redis缓存失败，请稍后重试！");
            }
        }
    }

}
